package com.demo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.Html;
import android.text.Html.ImageGetter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.demo.AsyncBitmapLoader.ImageCallBack;
import com.demo.R;

/**
 * 微博列表适配器
 * @author norsie
 * @create 12-12-20
 */
public class HomeListviewAdapter extends BaseAdapter
{

    private Context mContext;
    private boolean isForward = false; // 是否为转发条目
    private ArrayList<HashMap<String, String>> mStatus;
    private AsyncBitmapLoader asyncBitmapLoader;
    /**
     * 微博内容，包括发布者、发布内容、转发数、评论数、附件（图片、视频、网址等，如果有）、被转发人（如果有）、被转发微博（如果有）、
     * 被转发微博附件（如果有）
     */

    private LayoutInflater mInflater;
    private Pattern urlPattern = Pattern.compile("http://t\\.cn/[A-Za-z0-9]+\\b"); // 微地址匹配
    private Matcher urlMatcher;
    private List<String> urlList;

    public HomeListviewAdapter(Context context,
            ArrayList<HashMap<String, String>> status)
    {
        this.mStatus = status;
        this.mContext = context;
        asyncBitmapLoader = new AsyncBitmapLoader();

        mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount()
    {
        // TODO Auto-generated method stub
        return mStatus.size();
    }

    @Override
    public Object getItem(int position)
    {
        // TODO Auto-generated method stub
        return mStatus.get(position);
    }

    @Override
    public long getItemId(int position)
    {
        // TODO Auto-generated method stub
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        // TODO Auto-generated method stub
        ViewHolder holder = null;
        if (convertView == null)
        {
            convertView = mInflater.inflate(R.layout.listview_item, null);
            holder = new ViewHolder();
            holder.publisher = (TextView) convertView.findViewById(R.id.publisher);
            holder.reposts = (TextView) convertView.findViewById(R.id.reposts);
            holder.comments = (TextView) convertView.findViewById(R.id.comments);
            holder.text = (TextView) convertView.findViewById(R.id.text);
            holder.forwarder = (TextView) convertView.findViewById(R.id.forwarder);
            holder.forwarderText = (TextView) convertView.findViewById(R.id.forwarderText);
            holder.pic = (ImageView) convertView.findViewById(R.id.pic);

            convertView.setTag(holder);
        }
        else
        {
            holder = (ViewHolder) convertView.getTag();
        }
        
        //状态初始化,一些共用且有默认值的控件初始化
        ((LinearLayout)convertView.findViewById(R.id.item_more)).setVisibility(View.VISIBLE);
        ((LinearLayout)convertView.findViewById(R.id.item_more)).setBackgroundColor(Color.parseColor("#eeeeee"));
        ((LinearLayout)convertView.findViewById(R.id.item_mian_for)).setVisibility(View.VISIBLE);
        

        String publisher = mStatus.get(position).get("publisher").toString();
        String reposts = mStatus.get(position).get("reposts").toString();
        String comments = mStatus.get(position).get("comments").toString();
        String text = mStatus.get(position).get("text").toString();
        String forwarder = mStatus.get(position).get("forwarder").toString();
        String forwarderText = mStatus.get(position).get("forwarderText").toString();
        String pic = mStatus.get(position).get("pic").toString();

        // 判断是否含有转发微博,并进行相应处理
        if (forwarder.equals(null) && forwarderText.equals(null)
                || forwarder.equals("") && forwarderText.equals(""))
        {
            // 转发模块隐藏
//            holder.forwarder.setText("");
//            holder.forwarderText.setText("");
            
            ((LinearLayout)convertView.findViewById(R.id.item_more)).setBackgroundColor(Color.WHITE);
            ((LinearLayout)convertView.findViewById(R.id.item_mian_for)).setVisibility(View.GONE);
        }

        // 内容填充
        holder.publisher.setText(publisher);
        holder.reposts.setText(reposts);
        holder.comments.setText(comments);
        holder.forwarder.setText(forwarder);
        holder.text.setText("");
        holder.forwarderText.setText("");
        // 对微博内容中的网址信息进行处理并赋值
        urlHandle(stringFilter(text), holder.text);
        urlHandle(stringFilter(forwarderText), holder.forwarderText);

        if (pic != null)
        {

            Bitmap bitmap = asyncBitmapLoader.loadBitmap(holder.pic, pic,
                    new ImageCallBack() {

                        @Override
                        public void imageLoad(ImageView imageView, Bitmap bitmap)
                        {
                            // TODO Auto-generated method stub
                            imageView.setImageBitmap(bitmap);
                        }
                    });
            if (bitmap == null)
            {
                // 无图片的时候使用默认图片
                holder.pic.setImageResource(R.drawable.ic_launcher);
            }
            else
            {
                holder.pic.setImageBitmap(bitmap);
            }
        }

        return convertView;
    }

    static class ViewHolder
    {
        TextView publisher; // 发布者
        TextView reposts; // 回复数
        TextView comments; // 评论数
        TextView text; // 微薄内容
        TextView forwarder; // 被转发人
        TextView forwarderText; // 被转发内容
        ImageView pic; // 微博附件：主要以图片为主，其他均使用标签提醒
    }

    /**
     * url處理
     * */
    private void urlHandle(String text, TextView tv)
    {
        urlList = new ArrayList<String>();
        urlMatcher = urlPattern.matcher(text);
        StringBuffer sb = new StringBuffer();
        while (urlMatcher.find())
        {
            urlMatcher.appendReplacement(sb, ""); // 查詢第一處匹配內容，將其刪除，然後將此之前的內容保存在sb中
            urlList.add(urlMatcher.group()); // 将匹配的内容添加到列表里

            tv.append(sb); // 將處理好的文職寫到textview中
            tv.append(Html.fromHtml("<img src='" + R.drawable.tag_web + "'/>",
                    imageGetter, null)); // 在匹配內容處插入圖片
            sb.setLength(0); // 清空sb內容
            urlMatcher.appendTail(sb); // 將未匹配的內容放入sb
            urlMatcher = urlPattern.matcher(sb); // 重新設置Pattern，以新的sb的內容進行查詢
            sb.setLength(0); // 清空sb以備後用

        }
        sb.setLength(0);
        urlMatcher.appendTail(sb);
        tv.append(sb);
    }

    // TextView中的图片处理
    ImageGetter imageGetter = new ImageGetter() {
        @Override
        public Drawable getDrawable(String source)
        {
            int id = Integer.parseInt(source);
            // 根据id从资源文件中获取图片对象
            Drawable drawable = mContext.getResources().getDrawable(id);
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(),
                    drawable.getIntrinsicHeight());
            return drawable;
        }
    };

    /**
     * 半角转换为全角,去除特殊字符或将所有中文标号替换为英文标号
     * 
     * @param str
     * @return
     */
    public static String stringFilter(String str)
    {
        char[] c = str.toCharArray();
        for (int i = 0; i < c.length; i++)
        {
            if (c[i] == 12288)
            {
                c[i] = (char) 32;
                continue;
            }
            if (c[i] > 65280 && c[i] < 65375)
                c[i] = (char) (c[i] - 65248);
        }
        str = new String(c);
        str = str.replaceAll("【", "[").replaceAll("】", "]").replaceAll("！", "!").replaceAll("：", ":"); // 替换中文标号
        String regEx = ""; // "[『』]"; // 清除掉特殊字符
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

}
